import { createFlatRequest } from '@sa/axios';
import { useAuthStore } from '@/store/modules/auth';
import { localStg } from '@/utils/storage';
import { getServiceBaseURL } from '@/utils/service';
// import { fetchRefreshToken } from '../api';
import type { RequestInstanceState } from './type';

// 创建独立的请求实例用于刷新token，避免无限循环
const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y';
const { baseURL } = getServiceBaseURL(import.meta.env, isHttpProxy);

const refreshTokenRequest = createFlatRequest<App.Service.Response>({
  baseURL,
  headers: {
    apifoxToken: 'XL299LiMEDZ0H5h3A29PxwQXdMJqWyY2'
  }
});

export function getAuthorization() {
  const token = localStg.get('token');
  const Authorization = token ? `Bearer ${token}` : null;

  return Authorization;
}

/** refresh token using independent request instance */
async function fetchRefreshTokenSafe(refreshToken: string) {
  return refreshTokenRequest<Api.Auth.LoginToken>({
    url: '/auth/refreshToken',
    method: 'post',
    data: {
      refreshToken
    }
  });
}

/** refresh token */
async function handleRefreshToken() {
  const { resetStore } = useAuthStore();

  const rToken = localStg.get('refreshToken');

  // 如果没有有效的 refreshToken，直接重置并返回失败
  if (!rToken || rToken.trim() === '') {
    console.warn('No valid refresh token found, logging out');
    resetStore();
    return false;
  }

  const { error, data } = await fetchRefreshTokenSafe(rToken);
  if (!error) {
    localStg.set('token', data.token);
    localStg.set('refreshToken', data.refreshToken);
    return true;
  }

  resetStore();

  return false;
}

// 增加全局防护机制
let refreshAttempts = 0;
let lastRefreshTime = 0;
const MAX_REFRESH_ATTEMPTS = 3;
const REFRESH_COOLDOWN = 5000; // 5秒冷却时间

export async function handleExpiredRequest(state: RequestInstanceState) {
  const now = Date.now();

  // 检查冷却时间
  if (now - lastRefreshTime < REFRESH_COOLDOWN) {
    console.warn('Token refresh in cooldown period, rejecting request');
    return false;
  }

  // 检查重试次数
  if (refreshAttempts >= MAX_REFRESH_ATTEMPTS) {
    console.warn('Max refresh attempts reached, logging out');
    const { resetStore } = useAuthStore();
    resetStore();
    refreshAttempts = 0;
    return false;
  }

  // 防止重复刷新 token
  if (state.refreshTokenFn) {
    return await state.refreshTokenFn;
  }

  refreshAttempts += 1;
  lastRefreshTime = now;

  state.refreshTokenFn = handleRefreshToken();
  const success = await state.refreshTokenFn;

  // 延迟清理，防止短时间内重复刷新
  setTimeout(() => {
    state.refreshTokenFn = null;
  }, 1000);

  // 成功后重置计数器
  if (success) {
    refreshAttempts = 0;
  }

  return success;
}

export function showErrorMsg(state: RequestInstanceState, message: string) {
  if (!state.errMsgStack?.length) {
    state.errMsgStack = [];
  }

  const isExist = state.errMsgStack.includes(message);

  if (!isExist) {
    state.errMsgStack.push(message);

    window.$message?.error(message, 1.5, () => {
      state.errMsgStack = state.errMsgStack.filter(msg => msg !== message);

      setTimeout(() => {
        state.errMsgStack = [];
      }, 5000);
    });
  }
}
